import React, { HtmlHTMLAttributes, useEffect, useRef, useState } from 'react'
import styles from "../sass/home.module.scss"
import { Button, Select, Input, Table, Pagination, Modal, message, DatePicker, Form } from 'antd';
import { PlusOutlined, SyncOutlined, EyeOutlined, DownloadOutlined, EditOutlined, UploadOutlined, DeleteOutlined, FileTextOutlined, ProfileOutlined } from '@ant-design/icons';
import projectService from "../service/project/getproject"
import { withRouter } from "react-router-dom";
import saveAs from "file-saver";
import moment from 'moment';
import Header from "../component/header"
function List(props: any) {

    const reportTypes = {
        'audit_report': '审计报告',
        'audit_report_for_manuscript': '审计报告(底稿预处理)',
        'prospectus': '募集说明书',
        'prospectus_chapters': '募集说明书(按章拆分)',
        'annual_report': '年报半年报',
        'company_policy': '公司章程',
        'trustee_agreement': '受托管理协议',
        'holder_meeting_rule': '持有人会议规则',
        'rating_report': '评级报告',
        'asset_pool': 'ABS 资产池统计',
        'abs_history_prospectus': 'ABS 历史发行说明书',
        'rmbs': 'RMBS',
        'npl': 'NPL',
        'clo': 'CLO',
        'responsible_credit_abs': '信贷ABS尽调',
        'project_situation': '项目情况报告',
        'prospectus_capital_replenishment_debt': '资本补充债-募集说明书',
        'inquiry_name_list': '发行公告-询价明细数据表',
        'issue_anc_fields_user_filled': '发行公告-用户填写字段表',
        'land_certificate': '土地证',
        'loan_contract': '借款合同',
        'credit_report': '信用报告',
        'transfer_voucher': '转账凭证',
        'responsible_abs_abn_prospectus': '企业ABS计划说明书/ABN募集说明书',
        'bond_post_supervision': '债券后督',
    }
    // const allowFileExts = {
    //     audit_report: [],
    //     audit_report_for_manuscript: [],
    //     prospectus: [],
    //     prospectus_chapters: [],
    //     annual_report: [],
    //     company_policy: [],
    //     trustee_agreement: [],
    //     holder_meeting_rule: [],
    //     rating_report: [],
    //     rmbs: [],
    //     rmbs_trust_contract: ["doc", "docx", "pdf"],
    //     rmbs_serve_contract: ["doc", "docx", "pdf"],
    //     rmbs_safekeeping_contract: ["doc", "docx", "pdf"],
    //     rmbs_lead_underwriter_contract: ["doc", "docx", "pdf"],
    //     rmbs_definition_table: ["doc", "docx", "pdf"],
    //     rmbs_law_responsible_investigation_report: ["doc", "docx", "pdf"],
    //     rmbs_law_response: ["doc", "docx", "pdf"],
    //     rmbs_accounting_response: ["doc", "docx", "pdf"],
    //     rmbs_rating_report: ["doc", "docx", "pdf"],
    //     rmbs_excel_fields: ["xls", "xlsx"],
    //     npl: [],
    //     npl_trust_contract: ["doc", "docx", "pdf"],
    //     npl_serve_contract: ["doc", "docx", "pdf"],
    //     npl_safekeeping_contract: ["doc", "docx", "pdf"],
    //     npl_lead_underwriter_contract: ["doc", "docx", "pdf"],
    //     npl_definition_table: ["doc", "docx", "pdf"],
    //     npl_law_responsible_investigation_report: ["doc", "docx", "pdf"],
    //     npl_law_response: ["doc", "docx", "pdf"],
    //     npl_accounting_response: ["doc", "docx", "pdf"],
    //     npl_rating_report: ["doc", "docx", "pdf"],
    //     npl_tax_response: ["doc", "docx", "pdf"],
    //     clo: [],
    //     clo_trust_contract: ["doc", "docx", "pdf"],
    //     clo_serve_contract: ["doc", "docx", "pdf"],
    //     clo_safekeeping_contract: ["doc", "docx", "pdf"],
    //     clo_lead_underwriter_contract: ["doc", "docx", "pdf"],
    //     clo_definition_table: ["doc", "docx", "pdf"],
    //     clo_law_responsible_investigation_report: ["doc", "docx", "pdf"],
    //     clo_law_response: ["doc", "docx", "pdf"],
    //     clo_accounting_response: ["doc", "docx", "pdf"],
    //     clo_rating_report: ["doc", "docx", "pdf"],
    //     clo_tax_response: ["doc", "docx", "pdf"],
    //     responsible_credit_abs: [],
    //     responsible_credit_abs_prospectus: ["doc", "docx", "pdf"],
    //     responsible_apply_report: ["doc", "docx", "pdf"],
    //     responsible_annual_report: ["doc", "docx", "pdf"],
    //     responsible_trust_contract: ["doc", "docx", "pdf"],
    //     project_situation: [],
    //     project_abs_abn_prospectus: ["doc", "docx", "pdf"],
    //     project_responsible_report: ["doc", "docx", "pdf"],
    //     project_approval_report: ["doc", "docx", "pdf"],
    //     project_history_report: ["doc", "docx", "pdf"],
    //     asset_pool: [],
    //     abs_history_prospectus: [],
    //     prospectus_capital_replenishment_debt: [],
    //     inquiry_name_list: [],
    //     issue_anc_fields_user_filled: [],
    //     land_certificate: [],
    //     loan_contract: [],
    //     credit_report: [],
    //     transfer_voucher: [],
    //     responsible_abs_abn_prospectus: [],
    //     bond_post_supervision: [],

    const { Search } = Input;
    const { Option } = Select;
    //表格页脚
    const footer = () => {
        return <div>
            <span >共{fileCount}条</span>
            <Pagination showQuickJumper
                defaultCurrent={1}
                total={fileCount}
                showSizeChanger
                onShowSizeChange={onShowSizeChange}
                onChange={onpageChange}
                pageSizeOptions={[10, 20, 30, 40, 50, 60]}
            />
        </div>
    }
    const defaultTitle = [ //常规表头
        { title: '创建时间', dataIndex: 'create_time', key: 'create_time' },
        {
            title: '解析状态', dataIndex: 'parse_status', key: 'upgradeNum',
            render: (parse_status: string) => {
                if (parse_status === "finished") {
                    return <Button style={{ background: "#F0F9EB", color: "#67C23A", border: "#E1F3D8" }}>解析完成</Button>
                } else if (parse_status === "init") {
                    return <Button >未解析</Button>
                } else if (parse_status === "failed") {
                    return <Button danger>解析失败</Button>
                } else {
                    return <Button >解析中</Button>
                }
            }
        },
        {
            title: '操作', dataIndex: 'file_name', key: 'creator', render(file_name: string, info: any) {
                if (file_name == "-") {
                    return <Button type="primary" onClick={() => {
                        setProjectId(info.project_id)
                        setUploadFileVisible(true)
                    }} icon={<UploadOutlined />}>点击上传文件</Button>

                } else {
                    if (info.parse_status === "finished") {
                        return <Button type="primary" icon={<EyeOutlined />} onClick={goToParseResult.bind(this, info.project_id)}>查看解析结果</Button>
                    }
                    else if (info.parse_status === "failed") {
                        return <Button disabled type="primary" icon={<EyeOutlined />}>查看解析结果</Button>
                    } else if (info.parse_status === "processing") {
                        return <Button disabled type="primary" icon={<EyeOutlined />} >解析中</Button>
                    }
                    else {
                        return <Button type="primary" icon={<ProfileOutlined />} onClick={parseFile.bind(this, info.project_id)}>解析文件</Button>
                    }
                }
            }
        },
    ]
    const [allowReports, setallowreports] = useState<{ value: string; label: string; }[]>([]) //项目类型列表
    const [selectReport, setSelcetReport] = useState("") //选中报告类型
    const [selectReportName, setSelectReportName] = useState("")
    const [reportTable, setReportTale] = useState<any>([]) //选中列表的表格表头
    const [reportList, setReportList] = useState<any>([]) //选中报告列表
    const [canSearchUser, setSearchUser] = useState(false) //是否可以搜索发行人
    const [fileCount, setFileCount] = useState(0) //文件数量总合
    const [pageSize, setpageSize] = useState(10) //每页显示数据条数
    const [pageCount, setpageCount] = useState(1) //当前页数
    const [projectId, setProjectId] = useState(0) //点击修改发行人时的报告的id
    const [isModalVisible, setIsModalVisible] = useState(false); //对话框是否隐藏
    const [newIssuerName, setNewIssuerName] = useState("") //修改发行人名字
    const [uploadFileVisible, setUploadFileVisible] = useState(false) //上传文件遮罩层
    const [allowFileExts, setAllowFileExts] = useState("") //允许上传文件类型
    const [fileList, setfileList] = useState<any>([]) //文件列表
    const [createItemVisible, setCreateItemVisible] = useState(false) //新建项目对话框是否隐藏
    const [dateString, setDateString] = useState("")
    const [addtypeList, setAddTypeList] = useState<Array<any> | undefined>() //新建项目对话框表头
    const [addReportType, setAddReportType] = useState<Array<any>>([])//新建项目选择的文件类型
    //解析文件名称
    let inputUploadFile: any = React.createRef()
    let i: any = useRef(0)
    let reportType: any = React.createRef()
    const parseFileName = (data: Array<object>, parsename: string = "file_name") => {
        let newData: Array<any> = []
        data.forEach((item: any, index: number) => {
            item.key = ++i.current
            if (item.children) {
                item.children = parseFileName(item.children)
            }
            let key = Object.keys(item[parsename])
            if (key[0] === undefined) {
                item[parsename] = "-"
            } else {
                let newfilename: Array<any> = []
                key.forEach((keys: string, index: number) => {
                    newfilename.push(`${keys}:${item[parsename][keys]}`)
                })
                item[parsename] = newfilename
            }
            newData.push(item)
        })
        return newData
    }
    //点击解析文件按钮
    const parseFile = async (value: number) => {
        let data = await projectService.parseFile({ projectId: value })
        if (data.detail === "开始解析") {
            message.success("开始解析文档")
        }
    }
    const getdata = async (value: string = "") => { //获取列表
        if (selectReport) {
            let { res: data, count } = await projectService.getaProject({ reportType: selectReport, pageSize, pageCount, issuerChineseName: value })
            //   console.log(data);

            setFileCount(count)
            if (data[0]) { //是否有发行人
                if (data[0].issuer_name) {
                    setSearchUser(true)
                } else {
                    setSearchUser(false)
                }
            } else {
                setSearchUser(false)
            }
            data = parseFileName(data)
            setReportList(data)
        }
    }
    const getTableType = async () => { //获取列表表头格式
        if (selectReport) {
            let data = await projectService.getProjectTable({ reportType: selectReport })
            //对表头处理
            // console.log(data);
            //新建项目如果有多种添加文件的类型
            if (data[0].addReportType) {
                setAddReportType(data[0].addReportType)
            }
            //新建项目的表头

            setAddTypeList(data[0].addType)


            let allowFileExts = ""
            data[0].allowFileExts.forEach((item: any, index: number) => {
                if (index < data[0].allowFileExts.length - 1) {
                    allowFileExts += `.${item},`
                } else { allowFileExts += `.${item}` }

            })
            setAllowFileExts(allowFileExts)
            data = data[0].tabletitle
            data.forEach((item: any) => {
                if (item.dataIndex === "file_name") {
                    item.render = (data: any, info: any) => {
                        if (typeof data == "string") {
                            return <div>_</div>
                        } else {
                            for (let index = 0; index < data.length; index++) {
                                return <div>{data[index]} <DownloadOutlined
                                    onClick={async () => {
                                        let fileName = data[index].split(":")[1]
                                        let result = await projectService.downLoadFile({ projectId: info.project_id, fileName })
                                        saveAs(result, fileName)
                                    }}
                                    style={{ color: "blue" }} /></div>
                            }
                        }
                    }
                }
                if (item.dataIndex === "issuer_name") {
                    item.render = (data: any, info: any) => {
                        return <div>{data}  <EditOutlined style={{ color: "blue" }} onClick={() => {
                            setProjectId(info.project_id)
                            showModal()
                        }} /></div>
                    }
                }
            })
            console.log(data);
            setReportTale([...data, ...defaultTitle])
        }
    }
    //跳转到指定的解析页面
    const goToParseResult = (projectId: number) => {

        // console.log(projectId);
        // console.log(selectReport);
        const w = window.open('about:blank');


        if (selectReport !== "audit_report") {
            //  props.history.push(`/parseresult/${projectId}`)
            (w as Window).location.href = `http://localhost:3000/#/parseresult/${projectId}`
        } else {
            (w as Window).location.href = `http://localhost:3000/#/reportparseresult/${projectId}`
            // props.history.push(`/reportparseresult/${projectId}`)
        }
        // 
    }
    //修改发行人遮罩层是否可见
    const handleOk = async () => { //提交对话框
        let data = await projectService.updateProject({ projectId, issuerName: newIssuerName })
        if (data.detail === "更新完成") {
            message.success('更新成功');
            getdata()
        } else {
            message.error("更新失败")
        }
        setNewIssuerName("")
        setIsModalVisible(false);
    };
    const handleCancel = () => {
        setNewIssuerName("")
        setIsModalVisible(false);
    };
    const showModal = () => {
        setIsModalVisible(true);
    };
    //上传文件遮罩层可见
    const uploadOk = () => {
        if (fileList.length) {
            fileList.forEach(async (item: any, index: number) => {
                const formData = new FormData();
                formData.append("file", item);
                formData.append("projectId", projectId as unknown as string);
                formData.append("kind", "normal");
                //  console.log(formData);
                let data = await projectService.uploadFile(formData)
                if (data.detail === "上传成功") {
                    message.success("上传成功")
                    getdata()
                }
            })
        }
        setUploadFileVisible(false)
    }
    const uploadCancel = () => {
        setfileList([])
        setUploadFileVisible(false)
    }
    //上传文件列表发生变化
    const fileListChange = () => {
        if (inputUploadFile.current.files[0]) {
            let fileName = inputUploadFile.current.files[0].name
            let ishave = fileList.some((Item: any) => Item.name === fileName)
            if (!ishave) {
                inputUploadFile.current.files[0].projectId = projectId
                inputUploadFile.current.files[0].kind = "normal"
                //  console.log(inputUploadFile.current.files[0].raw);
                setfileList([...fileList, inputUploadFile.current.files[0]])
            }
        }
    }
    //新建项目表单提交
    const onFinish = async (values: any) => {  //提交表单
        //   console.log(typeof values.reportYear._d.getFullYear());
        let data: any = {}
        if (values.reportType) {
            data.reportType = selectReport
        }

        if (values.fileType) {
            data.fileType = values.fileType.split("（")[0]
        } if (values.issuerName) {
            data.issuerName = values.issuerName
        } if (values.reportYear) {
            data.reportYear = values.reportYear._d.getFullYear()
        }
        //console.log(data);
        let result = await projectService.createProject(data)
        if (result.project_id) {
            message.success("添加成功")
            getdata()
        }
        setCreateItemVisible(false)
    };

    const dateChange = (date: any, datestring: string) => {  //时间切换时候的函数
        //    console.log(date);
        setDateString(datestring)

    }
    useEffect(() => { //组件挂载时触发
        let options: { value: string; label: string; }[] = []
        Object.keys(reportTypes).forEach((value) => {
            options.push({ value, label: reportTypes[value as keyof typeof reportTypes] });
        });
        setSelcetReport(options[0]["value"])
        setSelectReportName(options[0]["label"])
        setallowreports(options)
    }, [])
    //搜索发行人
    const onSearch = ((value: string) =>
        getdata(value)
    )
    const handleChange = (value: string) => { //切换文件类型
        //   console.log(value);
        let type = allowReports.filter((item: any) => item.value === value)
        setSelectReportName(type[0].label)
        setSelcetReport(value)
    }
    useEffect(() => { //监听选择的报告类型，发生变化重新调接口发请求获取数据
        if (selectReport) {
            getdata()
            getTableType()
        }
    }, [selectReport])
    useEffect(() => { getdata() }, [pageSize, pageCount]) //每页数据显示数量发生改变
    //表格页脚
    const onpageChange = (value: number) => {
        setpageCount(value)
    }
    const onShowSizeChange = (current: number, pagesize: number) => {
        setpageSize(pagesize)
    }

    return (
        <div>
            {/* 头部 */}
            <Header></Header>


            {/* 创建项目，按钮 */}
            <div className={styles.buttons}>
                <Button type="primary" icon={<PlusOutlined />} size="large" style={{
                    marginRight: "10px"
                }} onClick={() => {
                    if (addtypeList != undefined) {
                        setCreateItemVisible(true)
                    } else {
                        setUploadFileVisible(true)
                    }

                }}>
                    新建项目
                </Button>
                <Button type="primary" icon={<SyncOutlined />} size="large" style={{
                    marginRight: "10px"
                }}
                    onClick={() => { getdata() }}>
                    刷新状态
                </Button>
                <Button type="primary" size="middle" disabled>
                    项目类型
                </Button>
                <Select onChange={handleChange} style={{ marginRight: "10px", width: 200 }}
                    value={selectReport}
                    id="reportype">
                    {allowReports.map((item: any, index: number) => {
                        return <Option key={index} value={item.value}>{item.label}</Option>
                    })}
                </Select>
                {canSearchUser ? <div>
                    <Button type="primary" size="middle" disabled>
                        发行人
                    </Button>
                    <Search placeholder="" onSearch={onSearch} style={{ width: 200 }} />
                </div> : ""}
            </div>
            {/* 数据表格 */}
            <div className={styles.reportTable}>
                <Table
                    className="components-table-demo-nested"
                    columns={reportTable}
                    dataSource={reportList}
                    pagination={false}
                    footer={footer}
                />
            </div>
            {/* 修改发行人姓名遮罩层 */}
            <Modal title="编辑发行人名称" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                <div> 发行人名称 <Input placeholder="请输入内容搜索发行人" style={{ width: "300px" }} value={newIssuerName}
                    onChange={(e) => {
                        setNewIssuerName(e.target.value)
                    }} /></div>
            </Modal>
            {/* 上传文件遮罩层 */}
            <Modal title="上传文件" visible={uploadFileVisible} onOk={uploadOk} onCancel={uploadCancel} >
                <input type="file" id="file" ref={inputUploadFile} style={{ display: "none" }} onChange={fileListChange} onClick={(e: any) => {
                    if (e.target.files.length) {
                        e.target.value = ""
                    } if (fileList.length) {
                        message.error("一次只能上传一份文件")
                        e.preventDefault()
                    }
                }} accept={allowFileExts}></input>
                <Button type="primary" icon={<UploadOutlined />}
                    onClick={() => {
                        inputUploadFile.current.click()
                    }}>
                    选取文件
                </Button>
                <br />
                <span style={{ fontSize: 12 }}>可上传的文件类型{allowFileExts}</span><br />
                {fileList.length === 0 ? "" : <div>
                    {fileList.map((item: any, index: number) => {
                        return <div className={styles.filesname} key={index}>
                            <span><FileTextOutlined />{item.name}</span>
                            <DeleteOutlined onClick={() => {
                                let filelist = fileList.filter((item: any, Index: number) => Index !== index)
                                setfileList(filelist)
                            }} />
                        </div>
                    })}
                </div>}
            </Modal>
            <Modal
                destroyOnClose={true}
                title="新建项目" visible={createItemVisible}
                footer={[]}
                onCancel={() => { setCreateItemVisible(false) }}
            >
                {addtypeList === undefined ? "" :
                    <Form
                        onFinish={onFinish}
                        initialValues={{ remember: true }}
                    >
                        {addtypeList.map((item: any, index: any) => {
                            if (item === "报告类型") {
                                return <Form.Item
                                    label="报告类型"
                                    name="reportType"
                                    key={index}
                                    rules={[{ required: true }]}
                                    initialValue={selectReportName}
                                >
                                    <Input defaultValue={selectReportName} disabled />
                                </Form.Item>

                            } else if (item === "报告年度") {
                                return <Form.Item
                                    label="报告年度"
                                    name="reportYear"
                                    key={index}
                                    rules={[{ required: true }]}
                                    initialValue={moment("2021")}
                                >
                                    <DatePicker
                                        defaultValue={moment("2021")}
                                        onChange={dateChange} picker="year" />
                                </Form.Item>
                                //
                            } else if (item === "发行人名称") {
                                return <Form.Item
                                    label="发行人名称"
                                    name="issuerName"
                                    key={index}
                                    rules={[{ required: true, message: '请输入发行人姓名' }]}>
                                    <Input placeholder="请输入内容搜索发行人" />
                                </Form.Item>
                            } else if (item === "债券全称") {
                                return <Form.Item
                                    label="债券全称"
                                    name="issuerName"
                                    key={index}
                                    rules={[{ required: true, message: '请输入债券全程' }]}>
                                    <Input />
                                </Form.Item>
                            } else if (item === "文件类型") {
                                return <Form.Item
                                    key={index}
                                    label="文件类型" name="fileType" rules={[{ required: true }]}
                                    initialValue="单年审计报告（pdf或word格式）"
                                >
                                    <Select defaultValue="单年审计报告（pdf或word格式）" style={{ width: 391 }}>
                                        {addReportType.map((item: any, index: number) => {
                                            return <Option key={index} value={item}>{item}</Option>
                                        })}
                                    </Select>
                                </Form.Item>

                            } else if (item === "公告披露日" || item === "报告期") {
                                return <Form.Item
                                    label={item}
                                    name="reportYear"
                                    key={index}
                                    rules={[{ required: true }]}
                                >
                                    <DatePicker onChange={dateChange} />
                                </Form.Item>
                            } else if (item === "评级机构名称") {
                                return <Form.Item label="评级机构名称" name="fileType" rules={[{ required: true }]} key={index}>
                                    <Select defaultValue="请选择评级机构" style={{ width: 362 }} >
                                        {addReportType.map((item: any, index: number) => {
                                            return <Option key={index} value={item}>{item}</Option>
                                        })}
                                    </Select>
                                </Form.Item>
                            }

                        })}
                        <Form.Item>
                            <div className={styles.createItemButton}>
                                <Button type="primary" htmlType="submit">
                                    确认
                            </Button>
                                <Button style={{ marginRight: "10px" }}
                                    onClick={() => { setCreateItemVisible(false) }}>
                                    取消
                            </Button>
                            </div>
                        </Form.Item>
                    </Form>
                }

            </Modal>
        </div>

    )
}
export default withRouter(List)